<template>
  <section class="block">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="基本信息" name="first">
        <el-form
          ref="competition"
          :model="competition"
          label-width="100px"
          :rules="competitionRules"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="比赛名称" prop="comName">
                <el-input v-model="competition.comName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="比赛地点" prop="address">
                <el-input v-model="competition.address"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="主办单位" prop="sponsor">
                <el-input v-model="competition.sponsor"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="承办单位" prop="undertaker">
                <el-input v-model="competition.undertaker"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="起始日期" prop="startDate">
                <el-date-picker
                  v-model="competition.startDate"
                  type="date"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd"
                  placeholder="选择起始日期"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束日期" prop="endDate">
                <el-date-picker
                  v-model="competition.endDate"
                  type="date"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd"
                  placeholder="选择结束日期"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="赛事级别" prop="comLevel">
                <el-select v-model="competition.comLevel" placeholder="请选择赛事级别">
                  <el-option
                    v-for="com in recomlevel"
                    :key="com.id"
                    :label="com.dictName"
                    :value="com.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="URL" prop="url">
                <el-input v-model="competition.url"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label>
                <el-checkbox v-model="isApply">允许裁判员报名</el-checkbox>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item v-show="isApply" label-width="100px" label="报名截止日期" prop="level">
                <el-date-picker
                  type="date"
                  placeholder="选择日期"
                  v-model="competition.applyEndDate"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

      <el-button type="primary" @click="createGame">提交</el-button>

      </el-tab-pane>

      <el-tab-pane label="裁判信息" name="addReTab" :disabled="addReTabDisabled">
        <h3>裁判信息</h3>
        <el-row>
          <el-col :span="24" align="right">
            <el-button type="primary" size="small" @click="showAddRefereeForm">增加人员</el-button>
          </el-col>
        </el-row>
        <!--列表-->
        <el-table
          :data="refereeList"
          highlight-current-row
          v-loading="listLoading"
          @selection-change="selsChange"
          style="width: 100%;"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column type="index" width="60"></el-table-column>
          <el-table-column prop="reName" label="姓名" width="120"></el-table-column>
          <el-table-column prop="jobId" label="职务" :formatter="formatRePosition" sortable></el-table-column>
          <el-table-column prop="reFrom" label="来源" :formatter="formatReFrom" ></el-table-column>
          <el-table-column prop="isConfirm" label="状态" :formatter="fromatisConfirm" ></el-table-column>

          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 增加人员模态框 -->
        <el-dialog title="添加人员" :visible.sync="addRefereeFormVisible" width="70%">
          <el-form ref="refereeForm" :model="refereeForm" :rules="refereeFormRule" label-width="50px">
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="职务" prop="jobId">
                  <el-select v-model="refereeForm.jobId" placeholder="请选择职务">
                    <el-option
                      v-for="level in repositionlevel"
                      :label="level.dictName"
                      :value="level.id"
                      :key="level.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="已选择" prop="name" label-width="80px">
                  <el-input v-model="refereeForm.name" readonly></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-form-item prop="reId" label-width="0">
                  <el-input type="hidden" v-model="refereeForm.reId"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <!-- 检索区域 -->
          <el-form :model="filteruser" ref="filteruser" label-width="50px">
            <el-row :gutter="10">
              <el-col :span="7">
                <el-form-item label="姓名">
                  <el-input v-model="filteruser.name"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="性别">
                  <el-select v-model="filteruser.gender" placeholder>
                    <el-option label="男" value="0"></el-option>
                    <el-option label="女" value="1"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item label="等级">
                  <el-select v-model="filteruser.level" placeholder>
                    <el-option
                      v-for="level in relevel"
                      :key="level.id"
                      :label="level.dictName"
                      :value="level.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label-width="0">
                  <el-button type="primary" @click="firstQueryUser">搜索</el-button>
                  <el-button type="success" @click="resetquery">清空</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <!-- 裁判员列表 -->
          <el-table
            :data="users"
            highlight-current-row
            v-loading="listLoading"
            style="width: 100%;"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <!-- <el-table-column type="index" width="60">
            </el-table-column>-->
            <el-table-column prop="name" label="姓名" width="100" sortable></el-table-column>
            <el-table-column prop="gender" label="性别" width="80" :formatter="formatSex" sortable></el-table-column>
            <el-table-column
              prop="level"
              label="级别"
              min-width="120"
              :formatter="formatReLevel"
              sortable
            ></el-table-column>
            <el-table-column prop="homeAddress" label="居住地" min-width="140" sortable></el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button size="small" @click="handleSelect(scope.$index, scope.row)">选择</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <el-col :span="24" class="toolbar">
              <!-- <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button> -->
              <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10" :total="total" style="float:right;">
              </el-pagination>
            </el-col>
          <div slot="footer" class="dialog-footer">
            <el-button @click="addRefereeFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="addreferee">确 定</el-button>
          </div>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>

  </section>
</template>


<script>
let id = 1000;
import mycommon from "../../common/enum";
import { getReLeve, getComLeve, getPositionLeve, getComRelist } from "../../api/api";
export default {
  data() {
    return {
      relevel: [],
      releveldict: {},
      recomlevel: [],
      recomleveldict: {},
      repositionlevel: [],
      repositionleveldict: {},
      activeName: "first",
      addReTabDisabled: false,
      rline: "",
      requiredChecked: false,
      checked: true,
      sels: [],
      isApply: false, // 临时的的是否允许报名，最种转化后为 0、1发送到后台
      comId:'',
      competition: {
        id: "",
        comLevel: "",
        startDate: "",
        endDate: "",
        comName: "",
        url: "",
        sponsor: "",
        undertaker: "",
        address: "",
        isApply: "",
        applyEndDate: "",
        adminChecked: ""
      },
      competitionRules: {
        comLevel: [
          { required: true, message: "请选择赛事级别", trigger: "chanage" }
        ],
        startDate: [
          {
            type: "string",
            required: true,
            message: "请选择开始日期",
            trigger: "change"
          }
        ],
        endDate: [
          {
            type: "string",
            required: true,
            message: "请选择开始日期",
            trigger: "change"
          }
        ],
        comName: [
          { required: true, message: "请选择赛事名称", trigger: "blur" }
        ],
        url: [],
        sponsor: [
          { required: true, message: "请输入主办单位", trigger: "blur" }
        ],
        undertaker: [
          { required: true, message: "请输入承办单位", trigger: "blur" }
        ],
        address: [
          { required: true, message: "请输入赛事地点", trigger: "blur" }
        ],
        isApply: [], // 发送到后台之前 这里需要转化一下
        applyEndDate: [],
        adminChecked: []
      },
      addRefereeFormVisible: false,
      filteruser: {
        name: "",
        gender: "",
        level: "",
        homeAddress: ""
      },
      refereeForm: {
        comId: 0,
        jobId: "", // 对应职务id
        reId: "",
        reFrom: "0",
        name: ""
      },
      refereeFormRule:{
        jobId:[{required: true, message:'选择职务', trigger:'change'}],
        name:[{required: true, message: '请选择裁判员', trigger:'change'}]
      },
      refereeList: [], // 待选择裁判列表
      users: [], // 裁判员表格数据
      total: 0, // 数据总条数
      page: 1, // 当前页面
      listLoading: false
    };
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab.name);
      if (tab.name === "addReTab") {
        if (this.competition.id) {
        } else {
          return false;
        }
      }
    },
    // formatSex: this.$filters.formatSex,
    formatReLevel(row) {
      return this.releveldict["lv" + row.level];
    },
    formatRePosition(row){
      return this.repositionleveldict["lv"+row.jobId]
    },
    formatReFrom(row){
      return row.reFrom === 0 ? '邀请' : '报名';
    },
    fromatisConfirm(row){
      return row.isConfirm ===0 ? '已确认' : '未确认';
    },
    // 性别显示转换
    formatSex(row) {
      return row.gender == 0 ? "男" : row.gender == 1 ? "女" : "保密";
    },
    // 分页的切换事件
    handleCurrentChange(val) {
      this.page = val;
      this.getUsers();
    },
    handleSelect(index, row){
      this.refereeForm.reId = row.id; //真正提交的是id
      this.refereeForm.name = row.name; //展现用
    },
    getUsers() {
      this.listLoading = true;
      let useroption = {
        pageNum: this.page,
        pageSize: 5,
        status: 0,
        delFlag: 0,
        name: this.filteruser.name,
        gender: this.filteruser.gender,
        level: this.filteruser.level,
        homeAddress: this.filteruser.homeAddress
      };
      // 获取裁判员数据
      this.axios
        .get("/referee/manage/re/page", { params: useroption })
        .then(response => {
          this.listLoading = false;
          this.total = response.data.data.total;
          this.users = response.data.data.list;
        })
        .catch(error => {
          this.listLoading = false;
          console.log(error);
        });
    },
    // 检索裁判员
    firstQueryUser() {
      this.page =1;
      this.getUsers();
    },
    resetquery(){
      this.filteruser = {
        name: "",
        gender: "",
        level: "",
        homeAddress: ""
      };
      this.getUsers();
    },
    // 添加执裁人员
    addreferee() {
      this.$refs.refereeForm.validate((valid)=>{
        if(valid){
          const recomdata ={
            comId: this.refereeForm.comId,
            jobId: String(this.refereeForm.jobId),  // 对应职务id
            reId: String(this.refereeForm.reId),
            reFrom: "0"
          }
          this.axios.post('/referee/manage/com/re', JSON.stringify(recomdata))
            .then((res) => {
              if(res.data.code === '0000'){
                this.$confirm('添加成功，是否继续添加下一个', '提示', {
                  confirmButtonText: '继续添加',
                  cancelButtonText: '取消',
                  type: 'success',
                })
                .then(()=>{
                  this.refereeForm.jobId = '';
                  this.refereeForm.reId = '';
                  this.refereeForm.name = '';
                }) 
                .catch(()=>{
                  this.addRefereeFormVisible = false;
                  this.refereeForm.jobId = '';
                  this.refereeForm.reId = '';
                  this.refereeForm.name = '';
                });
                
              }else{
                this.$message()
              }
            }).catch((err) => {
              
            });
        }else{
          this.$message('请选择选择职务和裁判员', 'warning');
        }
      })
    },
    showAddRefereeForm() {
      this.addRefereeFormVisible = true;
    },
    append(data) {
      const newChild = { id: id++, label: "testtest", children: [] };
      if (!data.children) {
        this.$set(data, "children", []);
      }
      data.children.push(newChild);
    },
    remove(node, data) {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex(d => d.id === data.id);
      children.splice(index, 1);
    },
    // 添加赛事
    createGame() {
      this.$refs.competition.validate(valid => {
        if (valid) {
          this.competition.isApply = this.isApply ? 0 : 1;
          const competitionJson = this.competition;
          competitionJson.startDate = this.GMTToStr(competitionJson.startDate);
          competitionJson.endDate = this.GMTToStr(competitionJson.endDate);
          // competitionJson.applyEndDate  截止日期 修改为 23：59：59

          console.log(this.competition.isApply, this.competition.comLevel);
          this.axios
            .post("/referee/manage/com", JSON.stringify(this.competition))
            .then(res => {
              console.log(res);
              if (res.data.code === "0000") {
                this.$message("添加比赛成功");
                this.competition.id = res.data.id;
                this.addReTabDisabled = false; // 赛事创建成功后才可以添加裁判员
              }
            })
            .catch(err => {
              console.log(err);
            });
        } else {
          return false;
        }
      });
    },
    selsChange(sels) {
      this.sels = sels;
    },
    GMTToStr: function(time) {
      let date = new Date(time);
      let Str =
        date.getFullYear() +
        "-" +
        (date.getMonth() + 1 <= 9
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) +
        "-" +
        (date.getDate() <= 9 ? "0" + date.getDate() : date.getDate()) +
        " " +
        (date.getHours() <= 9 ? "0" + date.getHours() : date.getHours()) +
        ":" +
        (date.getMinutes() <= 9 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":" +
        (date.getSeconds() <= 9 ? "0" + date.getSeconds() : date.getSeconds());
      return Str;
    },
    StrToGMT(time) {
      let GMT = new Date(time);
      return GMT;
    },
    // 获取执裁列表
    getComRelist(){
      const param = {
        comId: this.comId
      };
      getComRelist(param)
      .then((res) => {
        if(res.data.code === '0000'){
          this.refereeList = res.data.data.list;
        }
      }).catch((err) => {
        
    });
    }
  },
  mounted() {
    console.log(mycommon.comlevel);
    this.comId = this.$route.query.comId;
    if(!this.comId){
      this.$router.push('/eventManagement');
    }else{
      console.log(this.comId);
      this.refereeForm.comId = parseInt(this.comId);
      this.axios.get(`/referee/manage/com/${this.comId}`)
      .then((res) => {
        if(res.data.code==='0000' && res.data.data){
          this.competition = res.data.data;
          this.isApply = res.data.data.isApply === 0 ? true : false;
          this.getComRelist()
        }else{
          this.$router.push('/eventManagement');
        }
      }).catch((err) => {
        
      });
    };
    // 初始化赛事级别
    getComLeve()
      .then(res => {
        if (res.data.code === "0000") {
          this.recomlevel = res.data.data.list.filter(level => {
            return level.isDel === 0;
          });
          this.recomlevel.forEach(level => {
            if (level.isDel === 0) {
              this.recomleveldict["lv" + level.id] = level.dictName;
            }
          });
        }
      })
      .catch(err => {});
    // 初始化职务级别
    getPositionLeve()
      .then(res => {
        if (res.data.code === "0000") {
          this.repositionlevel = res.data.data.list.filter(level => {
            return level.isDel === 0;
          });
          this.repositionlevel.forEach(level => {
            if (level.isDel === 0) {
              this.repositionleveldict["lv" + level.id] = level.dictName;
            }
          });
        }
      })
      .catch(err => {});
    // 初始化裁判员等级
    getReLeve()
      .then(res => {
        if (res.data.code === "0000") {
          this.relevel = res.data.data.list.filter(level => {
            return level.isDel === 0;
          });
          this.relevel.forEach(level => {
            if (level.isDel === 0) {
              this.releveldict["lv" + level.id] = level.dictName;
            }
          });
          this.getUsers();
        }
      })
      .catch(err => {});
  }
};
</script>